package cn.wolfcode.web.controller;

import cn.wolfcode.anno.RequirePermission;
import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequirePermission(name = "角色查询",expression = "role:list")
    public String List(QueryObject qo, Model model){
        model.addAttribute("qo",qo);
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }

    @RequestMapping("/input")
    @RequirePermission(name = "角色新增和修改",expression = "role:saveOrUpdate")
    public String input(Long id, Model model){
        if (id != null){
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role",role);
        }
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);
        // 查询角色所拥有的权限
        List<Permission> ownPermissions = permissionService.queryPermissionByRoleId(id);
        model.addAttribute("ownPermissions",ownPermissions);

        return "role/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "角色新增和修改",expression = "role:saveOrUpdate")
    public String saveOrUpdate(Long[] permissionIds , Role role){
        if (role.getId() == null){
            roleService.insert(role,permissionIds);
        }else {
            roleService.updateByPrimaryKey(role,permissionIds);
        }
        return "redirect:/role/list";
    }

    @RequestMapping("/delete")
    @RequirePermission(name = "角色删除",expression = "role:delete")
    public String delete(Long id){
        roleService.deleteByPrimaryKey(id);
        return "redirect:/role/list";
    }


}
